package cn.lkp.mall.product.web;

import cn.lkp.mall.product.entity.CategoryEntity;
import cn.lkp.mall.product.service.CategoryService;
import cn.lkp.mall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        List<CategoryEntity> categoryEntities = categoryService.selectLevel1Categories();
        model.addAttribute("categories",categoryEntities);
        //视图解析器进行拼串
        //前缀默认值为prefix: classpath:/templates/
        //后缀默认值为：.html
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String,List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        RLock mylock = redisson.getLock("mylock");
        //mylock.lock();//阻塞式等待，默认加的锁有效期为30s
        //1.锁的自动续期，不用担心因为业务时间超长导致锁过期被删掉，运行期间自动续期30s
        //2.加锁的业务只要运行完成，就不会给锁续期，即使不手动解锁，锁默认在30s后自动删除。
        //自定义锁的超时时间10s,经过测试，业务执行时间需要30s，锁过期后，不会自动续期。因此指定的时间一定要超过业务执行的时间。
        //mylock.lock(10, TimeUnit.SECONDS);
        //1.如果指定了锁的超时时间，就会去占锁，默认超时就是指定的时间
        //2.如果未指定锁的超时时间，就默认使用看门狗的超时时间30s，只要占锁成功，就会每经过1/3个看门狗默认时间，启动定时任务（重新给锁设定超时时间，新的过期时间就是看门狗的默认时间）

        //最佳实战,设置足够的时间以便完成业务执行，手动解锁
        mylock.lock(35,TimeUnit.SECONDS);
        try{
            System.out.println("加锁成功，执行业务代码..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch(Exception e){}
        finally {
            System.out.println("释放锁..."+Thread.currentThread().getId());
            mylock.unlock();
        }
        return "hello";
    }
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //保证一定能读到最新数据，修改期间，写锁就是一个排他锁，互斥锁，读锁就是一个共享锁，写锁没释放读锁就必须等待。
    //读+读 无锁状态，所有读锁同时加锁
    //写+读 等待写锁释放
    //写+写 阻塞式
    //读+写 有读锁，写锁也需要等待
    @ResponseBody
    @GetMapping("/write")
    public String write(){
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock wLock = lock.writeLock();
        wLock.lock();
        System.out.println("写锁加锁成功"+Thread.currentThread().getId());
        try{
           s = UUID.randomUUID().toString();
           Thread.sleep(30000);
           stringRedisTemplate.opsForValue().set("write",s);
        }catch(Exception e){}
        finally {
            wLock.unlock();
            System.out.println("写锁释放成功"+Thread.currentThread().getId());
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        String s1 = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();
        System.out.println("读锁加锁成功"+Thread.currentThread().getId());
        try{
            Thread.sleep(30000);
            s1 = stringRedisTemplate.opsForValue().get("write");
        }catch(Exception e){}
        finally {
            rLock.unlock();
            System.out.println("读锁释放成功"+Thread.currentThread().getId());
        }
        return s1;
    }
    /**
     * 车库停车，车位park有3个，有空余车位了才可以停车
     * 可以用来做限流
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //阻塞式抢车位
        park.acquire();
        return "ok";
        //tryAcquire 试着去抢车位，抢不到就算了
//        boolean b = park.tryAcquire();
//        if(b){
//            //执行业务
//
//        }else {
//            return "error";
//        }
//        return "ok->"+b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        return "ok";
    }
    /**
     * 学校放假，两个班的人都走了，学校才能锁门
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(2);
        door.await();
        return "学校锁门了...";
    }
    @ResponseBody
    @GetMapping("/leave/{id}")
    public String leave(@PathVariable("id") Long id) throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数减一
        return id+"班的人都走了";
    }
}
